/**
 * @Description:登录主入口
 * @author 云离
 * @date: 2018/12/28
 */
import React, { Component } from "react";
import qs from "qs";
import md5 from "md5-node";
import { actions } from "../../../../reducers/main";
import { connect } from "react-redux";
import { withRouter } from "react-router-dom";
import {
  message,
  Spin,
  Table,
  Switch,
  Button,
  Icon,
  Pagination,
  Modal,
  Input,
  Popover
} from "antd";
import MyForm from "../../../components/Form";
import axios from "../../../../apis/api";
import AddUserForm from "../../charts/businessSummary/addUserForm";
import UserForm from "./addUserForm";

const { confirm } = Modal;

const mapStateToProps = (state, ownProps) => {
  return {
    vwAgentCashStat: state.main.vwAgentCashStat,
    vwAgentCashDayStat: state.main.vwAgentCashDayStat
  };
};

const mapDispatchToProps = dispatch => {
  return {
    fetchInitData: next => dispatch(actions.fetchInitData(next))
  };
};

const formItems = [
];

class UserMng extends Component {
  state = {
    initForm: {
      deptId: "",
      loginName: "",
      "params[userId]": "",
      status: "",
      "params[beginTime]": null,
      "params[endTime]": null,
      userName: ""
    },
    formItmes: formItems,
    searchParam: {},
    loading: false,
    depMap: {},
    pageSize: 10,
    curPage: 1,
    tableData: {
      total: 0,
      rows: []
    },
    pauseOrderVisible: false,
    curSelData: {},
    scoreVisible: false,
    scoreValue: 0,
    resetVisible: false,
    resetValue: 0,
    initCardForm: {},
    visibleDlg: false,
    cardFormTitle: "",
    cardFormType: "add",
    payVisible: false,
    payValue: "",
    pwdVisible: false,
    pwdValue: "",
    userDlg: false // 添加管理员 和 添加业务员 是否可见
  };
  componentDidMount() {
    this.init();
  }

  handleSearch = value => {
    this.setState(
      {
        curPage: 1,
        searchParam: value
      },
      this.searchTable
    );
  };

  componentDidMount() {
    this.init();
  }

  init = async () => {
    try {
      this.setState({
        loading: true
      });
      this.searchTable();
    } catch (e) {
      message.error(e.message);
    }
    this.setState({
      loading: false
    });
  };

  searchTable = async () => {
    const { pageSize, curPage, searchParam, depMap } = this.state;
    const query = {
      orderByColumn: "createTime",
      isAsc: "desc",
      pageSize,
      pageNum: curPage,
      deptId: searchParam.deptId,
      loginName: searchParam.loginName,
      "params[userId]": (searchParam.params && searchParam.params.userId) || "",
      status: searchParam.status,
      "params[beginTime]":
        (searchParam.params &&
          searchParam.params.beginTime &&
          searchParam.params.beginTime.format("YYYY-MM-DD")) ||
        "",
      "params[endTime]":
        (searchParam.params &&
          searchParam.params.endTime &&
          searchParam.params.endTime.format("YYYY-MM-DD")) ||
        "",
      userName: searchParam.userName,
      parentId:
        (searchParam.deptId &&
          depMap[searchParam.deptId] &&
          depMap[searchParam.deptId].pId) ||
        ""
    };
    try {
      this.setState({
        loading: true
      });
      const result = await axios.post("/system/config/list", qs.stringify(query));
      console.log(result);
      if (result.code === 0) {
        this.setState({
          tableData: result,
          loading: false
        });
      } else {
        this.setState({
          loading: false
        });
        message.error(result.msg);
      }
    } catch (e) {
      this.setState({
        loading: false
      });
      message.error(e.message);
    }
  };
  // 删除用户
  delUser = data => {
    Modal.confirm({
      title: "系统提示",
      content: "确定删除该条用户信息吗？",
      okText: "确定",
      cancelText: "取消",
      onOk: async () => {
        await axios.post(
          "/system/config/remove",
          qs.stringify({
            ids: data.configId
          })
        );
        message.success("删除成功");
        this.init();
      }
    });
  };

  //翻页
  handlePageChange = (page, pageSize) => {
    this.setState(
      {
        curPage: page
      },
      this.searchTable
    );
  };

  onShowSizeChange = (current, pageSize) => {
    this.setState(
      {
        pageSize: pageSize,
        curPage: current
      },
      this.searchTable
    );
  };
  editUser = card => {
    this.setState({
      userDlg: true,
      cardFormType: "edit",
      initCardForm: card,
      cardFormTitle: "修改"
    });
  };
  render() {
    const {
      initForm,
      formItmes,
      loading,
      tableData,
      curPage,
      pageSize
    } = this.state;
    const columns = [
      {
        title: "参数名称",
        dataIndex: "configName",
        key: "configName"
      },
      {
        title: "参数键名",
        dataIndex: "configKey",
        key: "configKey"
      },
      {
        title: "参数键值",
        dataIndex: "configValue",
        key: "configValue"
      },
      {
        title: "备注",
        dataIndex: "remark",
        key: "remark"
      },
      {
        title: "操作",
        key: "action",
        render: (text, record) => (
          <div>
            <Button
              type="primary"
              size={"small"}
              onClick={() =>this.editUser(record)}
            >
              编辑
            </Button>
            <Button
              type="danger"
              size={"small"}
              style={{ marginLeft: 10 }}
              onClick={() => this.delUser(record)}
            >
              删除
            </Button>
          </div>
        )
      }
    ];
    return (
      <div>
        <Spin spinning={loading}>
          <Table
            rowKey={record => record.configId}
            dataSource={tableData.rows}
            columns={columns}
            pagination={false}
          />
          <Pagination
            style={{ marginTop: 10, marginBottom: 20 }}
            total={tableData.total}
            showTotal={total => `共 ${total} 项`}
            pageSizeOptions={["10", "20", "50", "100", "500"]}
            showSizeChanger
            onShowSizeChange={this.onShowSizeChange}
            pageSize={pageSize}
            current={curPage}
            onChange={this.handlePageChange}
          />
          <UserForm
            visible={this.state.userDlg}
            initForm={this.state.initCardForm}
            title={this.state.cardFormTitle}
            cardFormType={this.state.cardFormType}
            okCb={() => {
              this.setState({ userDlg: false });
              this.init();
            }}
            cancelCb={() => this.setState({ userDlg: false })}
          />
        </Spin>
      </div>
    );
  }
}

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(withRouter(UserMng));
